<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="filters">
				<el-form-item>
					<el-input v-model="filters.keyword" placeholder="关键字"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="getEmployees">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--列表-->
		<el-table :data="employees" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
			<el-table-column type="selection" width="55">
			</el-table-column>
			<el-table-column type="index" width="60">
			</el-table-column>
			<el-table-column prop="username" label="姓名" width="130" sortable>
			</el-table-column>
			<el-table-column prop="email" label="邮箱" width="160" sortable>
			</el-table-column>
			<el-table-column prop="phone" label="电话" width="140" sortable>
			</el-table-column>
			<el-table-column prop="age" label="年龄" width="130" sortable>
			</el-table-column>
			<el-table-column prop="state" label="状态" width="130" sortable>
				<template scope="scope">
					<span style="color: green" v-if="scope.row.state == 1 ">正常</span>
					<span style="color: red" v-else-if="scope.row.state == 2 ">禁用</span>
					<span style="color: gray" v-else>未知</span>
				</template>
			</el-table-column>
			<el-table-column prop="department.name" label="部门" min-width="130" sortable>
			</el-table-column>
			<el-table-column label="操作">
				<template scope="scope">
					<el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
					<el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!--工具条-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
			<el-pagination layout="prev, pager, next" @current-change="handleCurrentChange"
						   :page-size="pageSize"
						   :total="total"
						   :current-page="page"
						   style="float:right;">
			</el-pagination>
		</el-col>

		<!--新增或编辑界面
		   :rules=  申明校验规则
		   ref= 绑定当前表当 取一个别名
		-->
		<el-dialog title="新增/编辑" :visible.sync="employeeFormVisible" :close-on-click-modal="false">
			<el-form :model="employeeForm" label-width="80px" :rules="employeeFormRules" ref="employeeForm">
				<el-form-item label="姓名" prop="username">
					<el-input v-model="employeeForm.username" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="邮箱" prop="email">
					<el-input v-model="employeeForm.email" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="电话" prop="phone">
					<el-input v-model="employeeForm.phone" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="年龄" prop="age">
					<el-input v-model="employeeForm.age" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="状态" prop="state">
					<el-radio-group v-model="employeeForm.state">
						<el-radio class="radio" :label="1">正常</el-radio>
						<el-radio class="radio" :label="2">禁用</el-radio>
					</el-radio-group>
				</el-form-item>
				<el-form-item label="部门" prop="department">
					<el-select v-model="employeeForm.department" value-key="id" placeholder="请选择">
						<el-option
								v-for="item in departments"
								:key="item.id"
								:label="item.name"
								:value="item">
							<span style="float: left">{{ item.name }}</span>
							<span style="float: right; color: #8492a6; font-size: 13px">{{ item.sn }}</span>
						</el-option>
					</el-select>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="employeeFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="save" :loading="employeeLoading">提交</el-button>
			</div>
		</el-dialog>
	</section>
</template>

<script>

	export default {
		data() {
			return {
				filters: {
					keyword: ''
				},
                departments: [],
				total: 0,
				pageSize:10,
				page: 1,
				listLoading: false,
				sels: [],//列表选中列
                employees:[],
				deptTree:[],//部门树集合

                employeeFormVisible: false,//新增/编辑界面是否显示
                employeeLoading: false,//忙等框
                employeeFormRules: {//申明校验规则
                    username: [
                        { required: true, message: '请输入姓名', trigger: 'blur' }

                    ],
                    password: [
                        { required: true, message: '请输入密码', trigger: 'blur' }
                    ]

                },

                //编辑界面数据
                employeeForm: {
                    id: null,
                    username: '',
                    email: '',
                    state: 0,
                    phone: '',
                    salt: '',
					password:'',
					age:'',
					department:null
                },
			}
		},
        methods: {
			handleCurrentChange(val) {
				this.page = val;
                this.getEmployees();
                this.getDepartments();
			},
			//获取部门列表
			getEmployees() {
				let para = {
					currentPage: this.page,
					keyword: this.filters.keyword
				};
				this.listLoading = true;

				/*发送axios请求，从后端拿数据*/
				this.$http.post("/employee",para)
					.then(result=>{
					this.total = result.data.total;
					this.employees = result.data.rows;
					this.listLoading = false;
				}).catch(result=>{
				    this.$message({
						message:"系统异常",
						type:'error',
					})
				});
			},
			//删除
			handleDel: function (index, row) {
				this.$confirm('确认删除该记录吗?', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
					//NProgress.start();
					let para = { id: row.id };
					this.$http.delete("/employee/"+row.id)
						.then(result=>{
						    result = result.data;
						    if(result.success){
						        this.$message({
									message:'删除成功',
									type:'success'
								});
						        this.page = 1;//如果删除成功定位到第一页
							}else {
                                this.$message({
                                    message:'删除失败'+ result.message,
                                    type:'error'
                                });
							}
                            this.getEmployees();//重新刷新页面
						})
				}).catch(() => {
                    this.$message({
                        message:'系统错误',
                        type:'error'
                    });
				});
			},
            //显示编辑界面
            handleEdit: function (index, row) {
                this.employeeFormVisible = true;//显示编辑窗口
                //Object.assign 克隆
                this.employeeForm = Object.assign({}, row);//回显数据
				console.log(Object.assign({}, row));
				this.getEmployees();
            },
            //显示新增界面
            handleAdd: function () {
                this.employeeFormVisible = true;//显示新增弹出框
                this.employeeForm={
                    id: null,
                    username: '',
                    email: '',
                    state: 0,
                    phone: '',
                    salt: '',
                    password:'',
                    age:'',
                    department:null
                };
			},
            //编辑
            save: function () {
                this.$refs.employeeForm.validate((valid) => {//在一次触发表单校验（理解）
                    if (valid) {
                        this.$confirm('确认提交吗？', '提示', {}).then(() => {
                            this.employeeLoading = true;
                            //NProgress.start();
                            let para = Object.assign({}, this.employeeForm);
                            this.$http.put("/employee",para)
								.then(result=>{
									result = result.data;
									this.employeeLoading = false;//关闭忙等框
									if (result.success){
									   this.$message({
										   message:'操作成功',
										   type:'success'
									   });
                                        this.page = 1;//定位到第一页
                                        this.getEmployees();//刷新页面
                                        this.employeeFormVisible = false;//关闭弹出框
									}else {
                                        this.$message({
                                            message:'操作失败'+result.message,
                                            type:'error'
                                        });
                                        this.employeeLoading = false;
									}
								})
								.catch(result=>{
                                    this.$message({
                                        message:'系统错误',
                                        type:'error'
                                    });
                                    this.employeeLoading = false;
								});
                        });
                    }
                });
            },
            selsChange: function (sels) {//选中的所有行sels
                this.sels = sels;
            },
			//批量删除
			batchRemove: function () {
				var ids = this.sels.map(item => item.id);
				this.$confirm('确认删除选中记录吗？', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
					this.$http.patch("/employee/",ids)
						.then(result=>{
					    	result = result.data;
					    	if (result.success){
					        	this.$message({
									message:'删除成功',
									type:'success'
								});
								this.page = 1;
							}else {
                            	this.$message({
									message:'删除失败'+result.message,
                                	type:'error'
                            	});
							}
						this.getEmployees();
					});
				}).catch(() => {
                    this.$message({
                        message:'系统错误',
                        type:'error'
                    });
				});
			},
            getDepartments(){
			    this.$http.get("/department")
					.then(result=>{
			        	result = result.data;
			        	if(result){
			        	    this.departments = result;
						}
					});
            }
		},
        mounted() {
            this.getEmployees();
		}
	}

</script>

<style scoped>

</style>